const ApiRes = require('../lib/utils/api-res')
const { buildTree } = require('../services/helper/route')
const RouteService = require('../services/route')

// 创建路由
async function createRoute(ctx) {
  const { compiled } = ctx.state
  const data = {
    ...compiled,
    buttons: JSON.stringify(compiled.buttons),
    query: JSON.stringify(compiled.query)
  }
  const result = await RouteService.create(data)
  ctx.body = ApiRes.success(result)
}

// 查询所有路由
async function findAllRoute(ctx) {
  const result = await RouteService.getMenuTree()

  ctx.body = ApiRes.success(result)
}

// 查询单个路由
async function findRouteById(ctx) {
  const { id } = ctx.params
  const result = await RouteService.findOne(id)
  if (result) {
    ctx.body = ApiRes.success(result)
  } else {
    ctx.body = ApiRes.error(404, '路由不存在')
  }
}

// 更新路由
async function updateRoute(ctx) {
  const { id } = ctx.params
  const { body } = ctx.request

  const result = await RouteService.update(id, body)
  if (result) {
    ctx.body = ApiRes.success(result)
  } else {
    ctx.body = ApiRes.error(404, '路由不存在')
  }
}

// 删除路由
async function deleteRoute(ctx) {
  const { id } = ctx.params
  const result = await RouteService.remove(id)
  if (result) {
    ctx.body = ApiRes.success(result)
  } else {
    ctx.body = ApiRes.error(404, '路由不存在')
  }
}

async function getAllPages(ctx) {
  const result = await RouteService.findAll().select('menu_name').pluck('menu_name')
  ctx.body = ApiRes.success(result)
}

async function getRoteIdsByRoleCode(ctx) {
  const result = await RouteService.getRoteIdsByRoleCode(ctx.params.roleCode)
  ctx.body = ApiRes.success(result)
}

async function getRouteMenuTree(ctx) {
  const result = await RouteService.findAll()
  ctx.body = ApiRes.success(buildTree(result))
}

module.exports = {
  createRoute,
  findAllRoute,
  findRouteById,
  updateRoute,
  deleteRoute,
  getAllPages,
  getRoteIdsByRoleCode,
  getRouteMenuTree
}
